<template>
	<el-select
		class="cl-select"
		ref="select"
		:value="value"
		v-bind="$props"
		v-on="$listeners"
		@visible-change="visibleChange"
		@change="change"
		@blur.native.capture="onblur"
		@hook:mounted="cancalReadOnly"
	>
		<slot slot="prefix" name="prefix" />
		<slot slot="empty" name="empty" />
		<slot></slot>
	</el-select>
</template>
<script>
import { addClass, removeClass } from "@/utils";
import { Select } from "element-ui";
export default {
	name: "cl-select",
	props: {
		...Select.props,
		filterPlaceholder: {
			type: String,
			default: "请输入关键字搜索"
		},
		// 需要手机筛选弹出键盘
		needKeyword: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			visible: false
		};
	},
	methods: {
		visibleChange(v) {
			this.visible = v;
			this.$emit("visible-change", v);
			this.cancalReadOnly(v)

			if (!this.multiple || !this.filterable) return;
			let el = this.$refs?.select?.$el?.querySelector?.(".el-select__input");
			el?.setAttribute?.("placeholder", this.filterPlaceholder);
			if (v) {
				el?.focus();
				addClass(el, "is-focus");
				return;
			}
			removeClass(el, "is-focus");
		},
		change(v) {
			// this.$emit("change", v);
			if (!this.multiple || !this.filterable) return;
			setTimeout(() => {
				this.$nextTick(() => {
					let select = this.$refs?.select?.$el;
					let tags = select?.querySelectorAll?.(".el-select__tags .el-tag");
					if (!tags.length) return;
					if (tags.length == 2) {
						tags[0].style.maxWidth = `calc(100% - ${tags[1].clientWidth + 15}px)`;
					} else {
						tags[0].style.maxWidth = "100%";
					}
				});
			});
		},
		// 失去焦点
		onblur() {
			if (!this.needKeyword) return false
			setTimeout(() => {
				if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
					//判断iPhone|iPad|iPod|iOS
					this.$refs.select.blur();
				}
				var scrollHeight =
					document.documentElement.scrollTop || document.body.scrollTop || 0;
				window.scrollTo(0, Math.max(scrollHeight - 1, 0));
			}, 100);
		},
		//取消只读
		cancalReadOnly(onOff) {
			if (!this.needKeyword) return false
			this.$nextTick(() => {
				if (!onOff) {
					const { select } = this.$refs;
					const input = select.$el.querySelector(".el-input__inner");
					input.removeAttribute("readonly");
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.cl-select {
	::v-deep {
		.el-select__tags {
			height: calc(100% - 2px);
			// z-index: 10;
			.el-tag {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
		.el-select__input {
			position: absolute;
			top: 0;
			left: 1px;
			margin-left: 2px;
			padding-left: 13px;
			width: 100% !important;
			height: calc(100% - 2px);
			background: #fff;
			opacity: 0;
			transition: opacity 0.15s linear;
			z-index: -1;

			&::placeholder {
				color: #c0c4cc;
				font-size: 12px;
			}
			&.is-focus {
				opacity: 1;
				z-index: 1;
			}
		}
	}
}
</style>
